/**
 * 公共函数封装
 * Create By wginit
 * Email: wginit@yeah.net
 */

class Util {
  constructor () {}
  showModal  = (title = '温馨提示', content = '', confirmText = '确定', fn, showCancel = false, confirmColor = '#f00', cancelColor = '#333') => {
    wx.showModal ({
      title: title,
      content: content,
      confirmText: confirmText,
      showCancel: showCancel,
      cancelColor: cancelColor,
      confirmColor: confirmColor,
      complete: function (res) {
       return typeof fn == 'function' && fn(res)
      }
    })
  }
  
  // Toast 显示框
  showToast = (title ='加载中', icon = 'loading', duration = 8000, image ='', mask = false, fn) => {
    wx.showToast({
      title: title,
      icon: icon,
      image: image,
      duration: duration,
      mask: mask,
      complete: function (res) {
        typeof fn === 'function' && fn(res)
      }
    })
  }
  
  // Toast 隐藏
  hideToast = () => {
    wx.hideToast()
  }
  // 函数节流
  throttle(fn, wait = 1500) {
    let _lastTime = null
    // 返回新的函数
    return function() {
      let _nowTime = +new Date()
      if (_nowTime - _lastTime > wait || !_lastTime) {
        fn.apply(this, arguments)
        _lastTime = _nowTime
      }
    }
  }

  // 数据储存到本地，同步
  setStorageSync (key, value, callback) {
    try {
      wx.setStorageSync(key, value)
      callback && callback('储存成功')
    } catch (err) {	
      this.showModal('温馨提示', '保存失败,' + err)
    }
  }

  // 从本地缓存中同步获取指定 key 对应的内容
  getStorageSync (key, callback) {
    try {
      var value = wx.getStorageSync(key)
      if (value) {
        callback && callback(value)
      }
    } catch (err) {
      this.showModal('温馨提示', '读取失败,' + err)
    }
  }
  // 移除本地缓存中指定内容
  removeStorageSync (key, callback) {
    try {
      wx.removeStorageSync(key)
      callback && callback()
    } catch (err) {
      this.showModal('温馨提示', '删除失败,' + err)
    }
  }

}
module.exports = new Util()